package com.zhongyu.controller;

import com.zhongyu.pojo.User;
import com.zhongyu.service.UserService;
import com.zhongyu.vo.PageResult;
import com.zhongyu.vo.ResultVo;
import com.zhongyu.vo.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.apache.shiro.crypto.hash.Md5Hash;
import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;


@RestController
@RequestMapping("/sys/user/")
@Slf4j
public class UserController {


    @Resource
    private UserService userService;

    @GetMapping("/list")
    public ResultVo list(UserVo userVo) {//表单数据提交@RequestParam json数据提交requestBody
        return ResultVo.success(userService.searchByUserVo(userVo));
    }
    @GetMapping("/sol")
    public ResultVo sol() {//表单数据提交@RequestParam json数据提交requestBody
        List<User> list= userService.searchAll();
        return ResultVo.success(list);
    }
    @GetMapping("/lists")
    public ResultVo list(){
        List<User> list= userService.searchAll();
        return  ResultVo.success(list);
    }
    /*   @GetMapping("/search/{pageNo}/{pageSize}")
       public ResultVo search(@PathVariable Integer pageNo,@PathVariable Integer pageSize,UserVo userVo){
           PageResult pageResult=userService.searchbyUserVo(pageNo,pageSize,userVo);
           return ResultVo.success(pageResult);*/
//Rest风格
    @GetMapping("/search/{pageNo}/{pageSize}")
    public ResultVo search(@PathVariable Integer pageNo, @PathVariable Integer pageSize, UserVo userVo) {
        PageResult pageResult = userService.searchAll(pageNo, pageSize, userVo);
        return ResultVo.success(pageResult);

    }
    @PostMapping("/select")
    public String select(@RequestBody User user){
        String result = userService.selectUserCode(user.getUserCode());
        if (result == null) {
            return "0";
        }
        return "1";

    }
    @PostMapping("/sp")
    public String sp(@RequestBody User user){
        String password=user.getPassword();

        String pwd02=new Md5Hash(password,"qwert").toString();

//        System.out.println("加盐"+pwd02);
        String username=user.getUsername();
        String result = userService.selectPassword(pwd02,username);
        if (result == null) {
            return "0";
        }
        return "1";
    }
    @PostMapping("/up")
public ResultVo up(@RequestBody User user ){
        try {
            String password=user.getNewPas();
            String newPas=new Md5Hash(password,"qwert").toString();
            String username=user.getUsername();
            userService.up(newPas, username);
            return ResultVo.success("修改密码成功!");
        } catch (RuntimeException ex) {
            return ResultVo.failure("修改密码失败！", ex);
        }
    }
    //重置密码
    @GetMapping("/updatePwd")//post请求要加@RequestBody进行接收
    public ResultVo updatePwd(User user) {
        try {
            String password=user.setPassword("123456");
             String newPas=new Md5Hash(password,"qwert").toString();
            String userCode=user.getUserCode();
            System.out.println(newPas);
            System.out.println(userCode);
            userService.updatePwd(newPas,userCode);
            return ResultVo.success("重置密码成功");
        } catch (Exception ex) {
            return ResultVo.failure("重置密码失败", ex);
        }

    }


    @GetMapping("/update")
    @RequiresPermissions("user:grant")
    public ResultVo update(Integer userId, Integer userRole) {
        try {
            userService.update(userId, userRole);
            return ResultVo.success("用户授权成功!");
        } catch (RuntimeException ex) {
            return ResultVo.failure("用户授权失败！", ex);
        }
    }

    @PostMapping("/update")//post请求要加@RequestBody进行接收
    public ResultVo update(@RequestBody User user) {
        try {
            userService.update(user);
            return ResultVo.success("修改角色成功");
        } catch (Exception ex) {
            return ResultVo.failure("修改用户失败", ex);
        }

    }

    @PostMapping("/add")
    @RequiresPermissions("user:add")
    public ResultVo add(@RequestBody User user) {

        try {
            user.setPassword("bacbc96d57da0555dc8b58beadbc2d93");
            user.setSalt("qwert");
            userService.add(user);
            return ResultVo.success("添加角色成功!");
        } catch (Exception ex) {
            return ResultVo.failure("添加角色失败!", ex);
        }
    }

    @PostMapping("/upload")
    public ResultVo upload(MultipartFile attach, HttpServletRequest request) {//ServletContext得加servlet-api-jar包,然而tomcat-embed-core这里面是包含servlet-api的,所以这里面就不用加servlet-api了
        ServletContext sc = request.getServletContext();//sc相当于jsp中的application内置对象
        String realPath = sc.getRealPath("/attach");//应用程序根目录下的绝对路径
//          System.out.println(realPath);
        File folder = new File(realPath);
        if (folder.exists() == false) {//判断attach目录是否存在，不存在会自动创建
            folder.mkdirs();
        }
        String original = attach.getOriginalFilename();//得到上传的原始文件名
        int index = original.lastIndexOf(".");
        String suffix = original.substring(index);//得到后缀名
        System.out.println("原始文件名:" + original);
//        String realPath="F:/项目/smbms01/src/main/webapp/attach";
        String newFileName = UUID.randomUUID().toString() + suffix;//为上传文件起一个新的唯一的文件名
        File file = new File(folder, newFileName);
        try {
            attach.transferTo(file);//执行上传
        } catch (IOException e) {
            e.printStackTrace();
        }
        Map<String, Object> map = new HashMap<>();
        map.put("attachPath", "attach/" + newFileName);
        return ResultVo.success(map);

    }

    @PostMapping("/updateAttach")
    public ResultVo updateAttach(@RequestBody User user) {
        try {
            userService.updateById(user);
            return ResultVo.success("上传并更新工作照信息成功");
        } catch (Exception ex) {
            return ResultVo.failure("上传并更新工作照信息失败!", ex);
        }
    }

    @GetMapping("/del")
    @RequiresPermissions("user:del")
    public ResultVo del(Integer id) {
        try {
            userService.del(id);
            return ResultVo.success("删除员工成功!");
        } catch (Exception ex) {

            return ResultVo.failure("删除员工失败！", ex);
        }


    }
}
